package leetcode.algorithm.linkedlist.simple.tree;

import leetcode.algorithm.TreeNode;

/**
 * 二叉搜索树的范围和
 * @author jiangwz
 * @create 2019/11/7.
 */
public class Q938 {

    public static void main(String[] args){

        TreeNode treeNode = new TreeNode(10);
        TreeNode treeNode1 = new TreeNode(5);
        TreeNode treeNode2 = new TreeNode(15);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(7);
        TreeNode treeNode5 = new TreeNode(18);

        treeNode.left = treeNode1;
        treeNode.right = treeNode2;
        treeNode1.left = treeNode3;
        treeNode1.right = treeNode4;
        treeNode2.left = null;

        System.out.println(new Q938().rangeSumBST(treeNode, 7, 15));
    }



    int count = 0;

    /**
     * leetcode-cn 这题的编译器有问题,怎么都过不了,官方答案也报错
     * @param root
     * @param L
     * @param R
     * @return
     */
    public int rangeSumBST(TreeNode root, int L, int R) {
        preOrder(root,L,R);
        return count;
    }

    public void preOrder(TreeNode node, int L, int R) {
        if (node != null){
            if (L<=node.val&& node.val<=R){
                count+=node.val;
            }
            if (node.left != null)
                preOrder(node.left,L,R);

            if (node.right != null)
                preOrder(node.right,L,R);
        }
    }
//    public void preOrder(TreeNode node, int L, int R) {
//        if (node != null){
//            if (L<=node.val&& node.val<=R){
//                count+=node.val;
//            }
//            if (node.left != null)
//                preOrder(node.left,L,R);
//
//            if (node.right != null)
//                preOrder(node.right,L,R);
//        }
//    }

}


